package org.adorsys.aderp.jpa.api.xchange;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class ObjectMapper {
	
	private DataView dataView;
	
	public ObjectMapper(DataView dataView) {
		this.dataView = dataView;
	}

	public Map<String, String> toMap(Object object){
		StandardEvaluationContext simpleContext = new StandardEvaluationContext(object);
		ExpressionParser parser = new SpelExpressionParser();
		Set<Entry<String,String>> entrySet = dataView.getFieldExpressions().entrySet();
		Map<String, String> result = new HashMap<String, String>();
		for (Entry<String, String> entry : entrySet) {
			String fieldExpression = entry.getValue();
			Expression expression = parser.parseExpression(fieldExpression);
			String value = expression.getValue(simpleContext, String.class);
			if(value!=null) result.put(entry.getKey(), value);
		}
		return result;
	}
}
